package Thread;

import java.util.Scanner;

public class Demo22 {
    public static void main(String[] args) {
        Object locker1 = new Object();
        Thread t1 = new Thread(()->{
            try{
                System.out.println("t1线程等待中，在wait之前");
                synchronized (locker1){
                    locker1.wait();
                }
                System.out.println("t2线程结束，在wait之后");
            }catch ( InterruptedException e){
                throw new RuntimeException();
            }
        });
        Thread t2 = new Thread(()->{
            try{
                System.out.println("t2线程等待中，在wait之前");
                synchronized (locker1){
                    locker1.wait(10000);
                }
                System.out.println("t2线程结束，在wait之后");
            }catch ( InterruptedException e){
                throw new RuntimeException();
            }
        });
        Thread t3 = new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入任意内容，唤醒t1");
            scanner.next();
            synchronized (locker1){
                locker1.notify();
            }
            System.out.println("请输入任意内容，唤醒t2线程");
            scanner.next();
            synchronized (locker1){
                locker1.notify();
            }
        });
        t1.start();
        t2.start();
        t3.start();
    }

    /**
     * notifyAll在工作中用的不多，主要使用notify一个一个线程来唤醒
     * @param args
     */
    public static void main1(String[] args) {
        Object locker1 = new Object();
        Thread t1 = new Thread(()->{
            try{
                System.out.println("t1线程等待中，在wait之前");
                synchronized (locker1){
                    locker1.wait();
                }
                System.out.println("t2线程结束，在wait之后");
            }catch ( InterruptedException e){
                throw new RuntimeException();
            }
        });
        Thread t2 = new Thread(()->{
            try{
                System.out.println("t2线程等待中，在wait之前");
                synchronized (locker1){
                    locker1.wait(10000);
                }
                System.out.println("t2线程结束，在wait之后");
            }catch ( InterruptedException e){
                throw new RuntimeException();
            }
        });
        Thread t3 = new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入任意内容，唤醒t1");
            scanner.next();
            synchronized (locker1){
                locker1.notifyAll();
            }
        });
        t1.start();
        t2.start();
        t3.start();
    }
}
